#include "fsmp_board/fsmpCamera.h"
#include <QDebug>
#include <linux/videodev2.h>
#include <sys/ioctl.h>
#include <sys/mman.h>

fsmpCamera::fsmpCamera(const char* dev, int w, int h, QObject* parent)
    : QThread(parent), m_dev(dev), m_w(w), m_h(h) {
    fd = ::open(dev, O_RDWR);
    if (fd < 0) {
        perror("open camera");
        return;
    }
    // 设置格式 MJPG 640x480
    struct v4l2_format fmt{};
    fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    fmt.fmt.pix.width = w;
    fmt.fmt.pix.height = h;
    fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG;
    fmt.fmt.pix.field = V4L2_FIELD_NONE;
    if (ioctl(fd, VIDIOC_S_FMT, &fmt) < 0) {
        perror("VIDIOC_S_FMT");
    }
}

void fsmpCamera::run() {
    while (true) {
        QImage img(m_w, m_h, QImage::Format_RGB32);
        // 简化：直接 read()，实际最好用 mmap + buffer queue
        QByteArray buf(m_w * m_h * 2, 0);
        int ret = ::read(fd, buf.data(), buf.size());
        if (ret > 0) {
            img.fill(Qt::black); // TODO: MJPG 解码成 QImage
            emit pixReady(img);
        }
        msleep(50);
    }
}
